"""
/*
 * Copyright 2011 OpenWAF.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
 """
import sys
import os
def processImport(odata, fname,cssVars):
        data = "".join(odata)
        #try:
        path, sep, cname = fname.rpartition(os.path.sep)
    
        index = data.index("(")
        data = data[index + 1:-1].strip()
        iname = data[1:-1].strip()
                
        if "\\" in iname  or "/" in iname:
            if "\\" in iname:
                if os.path.sep != "\\":
                    iname = iname.replace("\\", os.path.sep)
            elif "/" in iname:
                if os.path.sep != "/":
                    iname = iname.replace("/", os.path.sep)
        path = path + os.path.sep + iname
        return processWAFcss(path,cssVars, True)

        """        
        except:
        print "=============================================================="
        print " ERROR: Unknown Error while importing css file             "
        print "--------------------------------------------------------------"
        print " File Name :",fname
        print " rawdata   :\""+"".join(odata)+"\""
        print "==============================================================="
        sys.exit(0)
        """    
            

def readCssVars(odata, cvars, fname):
    
        data = "".join(odata)
        #try:
        index = data.index("{")
        data = data[index + 1:-1]
        vs = data.split(";")
        for v in vs:
            if len(v.strip()) == 0:continue
            parts = v.split(":")
            name = parts[0].strip()
            value = parts[1].strip()
            if cvars.has_key(name):
                print "======================================="
                print " ERROR: Duplicate Css variable found   "
                print "---------------------------------------"
                print " File Name :", fname
                print " Variable  :\"" + name + "\""
                print "======================================="
                sys.exit(0)
            cvars[name] = value
        """
        except:
        
        print "=============================================================="
        print " ERROR: Unknown Error while parsing css file for @variables   "
        print "--------------------------------------------------------------"
        print " File Name :",fname
        print " rawdata   :\""+"".join(odata)+"\""
        print "==============================================================="
        sys.exit(0)
            """

def getVarValue(data, cvars, fname): # fname just display error message
    index = data.index("(")
    data = "".join(data)
    varname = data[index + 1:-1].strip()
    if cvars.has_key(varname):
        return cvars[varname]
    else:    
        print "======================================="
        print " ERROR: Css variable not found   "
        print "---------------------------------------"
        print " File Name :", fname
        print " Variable  :\"" + varname + "\""
        print "======================================="
        sys.exit(0)
        
    
    
def processWAFcss(fname,cssVars, being_imported=False):
    #print "Processing Css", fname
    lines = open(fname).readlines()
    data = "".join(lines)
    c = 0
    mc = len(data)
    ndata = []
    while c < mc:
        if data[c] == "@" and data[c:].startswith("@variables"):
            block = []
            while data[c] != "}":
                block.append(data[c])
                c += 1
            block.append(data[c])
            readCssVars(block, cssVars, fname)
        elif data[c] == "@" and data[c:].startswith("@must-import"):
            if being_imported == False:
                return None
            c += 11 # skiping must-import
        elif data[c] == "@" and data[c:].startswith("@css-import"):
            block = []
            while data[c] != ")":
                block.append(data[c])
                c += 1
            block.append(data[c])            
            ndata.append(processImport(block, fname,cssVars))
            
        elif data[c] == "v" and data[c:].startswith("var("):
            vardata = []
            while data[c] != ")":
                vardata.append(data[c])
                c += 1
            vardata.append(data[c])
            ndata += getVarValue(vardata, cssVars, fname)
        else:
            ndata.append(data[c])
        c += 1
            
    return "".join(ndata)
    
    

if __name__ == "__main__":
    cssVars={}
    print processWAFcss(sys.argv[1],cssVars)

